<template>
  <div class="d">
    <el-dialog
      :title="title"
      width="600px"
      :visible.sync="show"
      @open="openCallback"
    >
      <div
        class="loading-view"
        v-loading="loading"
        element-loading-text="加载中"
        v-if="loading"
      ></div>
      <el-form :model="form" ref="form" v-if="typeLists.length > 0 && show">
        <template v-for="(item, index) in typeLists">
          <el-form-item
            :label="item.data.title"
            :label-width="formLabelWidth"
            :key="index"
          >
            <el-input
              v-model="form[item.type]"
              :disabled="disabled"
              clearable
              autocomplete="off"
              :placeholder="
                type == 'edit' ? '请输入' + item.data.title : '暂无'
              "
              v-if="item.data.type == 'input'"
            ></el-input>
            <el-input
              type="textarea"
              v-model="form[item.type]"
              :disabled="disabled"
              clearable
              maxlength="500"
              show-word-limit
              :placeholder="
                type == 'edit' ? '请填写' + item.data.title : '暂无'
              "
              v-if="item.data.type == 'textarea'"
            ></el-input>
            <el-select
              v-model="form[item.type]"
              :disabled="disabled"
              clearable
              :placeholder="
                type == 'edit' ? '请选择' + item.data.title : '暂无'
              "
              v-else-if="
                item.data.type == 'select' && item.data.value.length > 0
              "
            >
              <el-option
                v-for="(item2, index2) in item.data.value"
                :key="'item2' + index2"
                :label="item2"
                :value="item2"
              >
              </el-option>
            </el-select>
            <el-autocomplete
              class="inline-input"
              v-model="form[item.type]"
              :fetch-suggestions="querySearch"
              :disabled="disabled"
              clearable
              :placeholder="
                type == 'edit' ? '请输入' + item.data.title : '暂无'
              "
              @select="handleSelect"
              @focus="focus(item.data.value)"
              v-else-if="item.data.type == 'inputselect'"
            ></el-autocomplete>
            <template v-if="item.data.type == 'upload'">
              <el-upload
                class="upload-demo"
                :disabled="disabled"
                :action="uploadUrl"
                :file-list="fileList"
                list-type="picture"
                :multiple="false"
                :limit="1"
                :headers="{ Accept: 'application/json, text/plain, */*, */*' }"
                name="inputFile"
                :data="uploadData"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :on-remove="removeFile"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
              <el-input
                v-model="form[item.type]"
                autocomplete="off"
                style="display: none"
              ></el-input>
            </template>
          </el-form-item>
        </template>
        <el-form-item v-if="!disabled">
          <el-button
            type="primary"
            @click="submitForm('form')"
            :loading="submitting"
            >{{ submitText }}</el-button
          >
          <el-button @click="show = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  getPropertyList,
  updateOrSaveProperty,
} from "@/api/ancientCity/index.js";
import { deepClone } from "@/utils/index";
import { getToken } from "@/utils/auth";
import { Notification } from "element-ui";
const txt = "保存";
export default {
  name: "edit",
  props: {
    item: Object,
    type: {
      type: String,
      default: "edit",
    },
  },
  data() {
    return {
      title: "",
      show: false,
      loading: true,
      submitting: false,
      submitText: txt,
      form: null,
      formLabelWidth: "110px",
      restaurants: [],
      typeLists: [],
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
        // {
        //   name: "food2.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
      types: {
        roamingUrl: {
          title: "漫游url",
          type: "input",
        },
        enName: {
          title: "古城英文惯例名",
          type: "input",
        },
        cnName: {
          title: "中文惯例名",
          type: "input",
        },
        localTextName: {
          title: "原名 (当地文字)",
          type: "input",
        },
        shortIntroduction: {
          title: "简介",
          type: "textarea",
        },
        fileId: {
          title: "文件",
          type: "upload",
        },
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/wcFile/upFile",
      uploadData: { token: getToken() },
      uoloadFileIds: [],
    };
  },
  computed: {
    disabled() {
      return this.type == "look";
    },
  },
  methods: {
    openCallback() {
      this.title = this.type == "edit" ? "编辑" : "查看";
      this.form = deepClone(this.item.oldCityProperty);
      this.fileList = this.form.imageUrl
        ? this.form.imageUrl.map((item, index) => {
            return {
              name: item,
              url: item,
              id: this.form.fileId.split(",")[index],
            };
          })
        : [];
      this.uoloadFileIds = this.form.fileId ? this.form.fileId.split(",") : [];
      this.form.id = this.item.id;
      this.typeLists = this.dealData(this.types);
      this.getPropertyList();
    },
    // 获取属性列表
    async getPropertyList() {
      this.loading = true;
      const req = getPropertyList();
      const res = await req;
      const newObj = Object.assign(res.data, this.types);
      this.typeLists = this.dealData(newObj);
      this.loading = false;
    },
    // 处理数据
    dealData(obj) {
      let list = [];
      for (let key in obj) {
        list.push({ type: key, data: obj[key] });
      }
      list.forEach((item) => {
        item.data.title = Array.isArray(item.data.title)
          ? item.data.title[0]
          : item.data.title;
        item.data.type = Array.isArray(item.data.type)
          ? item.data.type[0]
          : item.data.type;
      });
      return list;
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect() {},
    focus(val) {
      this.restaurants = val.map((item) => {
        return { value: item };
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitting = true;
          this.submitText = "提交中";
          this.save();
        } else {
          return false;
        }
      });
    },
    async save() {
      this.form.oldCityId = this.form.id;
      this.form.fileId = this.uoloadFileIds.join(",");
      delete this.form.id;
      delete this.form.imageUrl;
      try {
        const req = updateOrSaveProperty(this.form);
        const res = await req;
        setTimeout(() => {
          this.$emit("update");
          this.show = false;
        }, 500);
      } catch (error) {}
      this.submitText = txt;
      this.submitting = false;
    },
    uploadSuccess(response, file) {
      this.uoloadFileIds.push(file.response.data.id);
      Notification({
        title: "成功",
        message: "上传成功",
        type: "success",
      });
    },
    uploadError() {
      Notification({
        title: "失败",
        message: "上传失败",
        type: "error",
      });
    },
    removeFile(file, fileList) {
      this.uoloadFileIds = fileList.map(
        (item) => item.id || item.response.data.id
      );
    },
  },
};
</script>
<style scoped>
>>> .el-select,
>>> .el-autocomplete {
  width: 100%;
}

>>> .el-dialog {
  min-height: 400px;
}

.loading-view {
  position: absolute;
  position: absolute;
  left: 0;
  top: 50px;
  bottom: 0;
  right: 0;
}
</style>
